package com.sadam.ui4.FragmentSelfPage.FragmentComposition;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.sadam.ui4.Data.Video;
import com.sadam.ui4.R;

import java.util.List;

public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {

    protected List<Video> videoList;
    private Context context;
    private OnVideoClickListener onVideoClickListener;
    private OnVideoLongClickListener onVideoLongClickListener; // 新增长按监听器

    // Glide请求配置（圆角、占位图等）
    private RequestOptions requestOptions;

    /**
     * 点击事件接口
     */
    public interface OnVideoClickListener {
        void onVideoClick(Video video, int position);
    }

    /**
     * 长按事件接口
     */
    public interface OnVideoLongClickListener {
        void onVideoLongClick(Video video, int position);
    }

    public VideoAdapter(List<Video> videoList, Context context) {
        this.videoList = videoList;
        this.context = context;

        // 初始化Glide配置
        initGlideOptions();
    }

    private void initGlideOptions() {
        requestOptions = new RequestOptions()
                .transform(new CenterCrop(), new RoundedCorners(16)) // 圆角16dp
                .placeholder(R.drawable.sample_cover) // 占位图
                .error(R.drawable.sample_cover) // 错误图
                .override(400, 600) // 指定图片尺寸，优化内存
                .dontAnimate(); // 禁用动画，提升性能
    }

    public void setOnVideoClickListener(OnVideoClickListener listener) {
        this.onVideoClickListener = listener;
    }

    // 新增：设置长按监听器
    public void setOnVideoLongClickListener(OnVideoLongClickListener listener) {
        this.onVideoLongClickListener = listener;
    }

    @NonNull
    @Override
    public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_video_card, parent, false);
        return new VideoViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
        Video video = videoList.get(position);

        // 设置标题
        holder.tvTitle.setText(video.getTitle());

        // 设置播放量（用点赞数代替）
        int likeCount = video.getLikeCount();
        String playCount = formatPlayCount(likeCount);
        holder.tvPlayCount.setText(playCount);

        // 使用Glide加载视频封面（关键改进）
        loadVideoCoverWithGlide(holder, video);

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (onVideoClickListener != null) {
                onVideoClickListener.onVideoClick(video, position);
            }
        });

        // 新增：设置长按事件
        holder.itemView.setOnLongClickListener(v -> {
            if (onVideoLongClickListener != null) {
                onVideoLongClickListener.onVideoLongClick(video, position);
                return true;
            }
            return false;
        });
    }

    /**
     * 使用Glide异步加载视频封面
     */
    private void loadVideoCoverWithGlide(VideoViewHolder holder, Video video) {
        String videoPath = video.getVideoFilePath();

        if (videoPath != null && !videoPath.isEmpty()) {
            // 使用Glide加载视频第一帧作为封面
            Glide.with(context)
                    .asBitmap()
                    .load(videoPath)
                    .apply(requestOptions)
                    .into(holder.ivCover);
        } else {
            // 视频路径为空，显示默认封面
            holder.ivCover.setImageResource(R.drawable.sample_cover);
        }
    }

    /**
     * 格式化播放量显示
     */
    private String formatPlayCount(int count) {
        if (count >= 10000) {
            return String.format("%.1fw", count / 10000.0);
        } else if (count >= 1000) {
            return String.format("%.1fk", count / 1000.0);
        } else {
            return String.valueOf(count);
        }
    }

    @Override
    public int getItemCount() {
        return videoList.size();
    }

    // 添加内存优化方法
    public void clear() {
        if (videoList != null) {
            videoList.clear();
            notifyDataSetChanged();
        }
    }

    /**
     * 更新数据列表
     */
    public void updateList(List<Video> newVideoList) {
        this.videoList.clear();
        this.videoList.addAll(newVideoList);
        notifyDataSetChanged();
    }

    static class VideoViewHolder extends RecyclerView.ViewHolder {
        ImageView ivCover;
        TextView tvPlayCount;
        TextView tvTitle;

        public VideoViewHolder(@NonNull View itemView) {
            super(itemView);
            ivCover = itemView.findViewById(R.id.ivCover);
            tvPlayCount = itemView.findViewById(R.id.tvPlayCount);
            tvTitle = itemView.findViewById(R.id.tvTitle);
        }
    }
}